/**
 * Created by sjg on 17/3/6.
 */

var express = require('express');
var router = express.Router();
var superagent = require('superagent');// 使用了superagent来发起请求
var ItbFeedbackModel = require('../../../common/mysql/mapping/ItbFeedbackModel');
var ItbTradeOrderDetailModel = require('../../../common/mysql/mapping/ItbTradeOrderDetailModel');
var ItbCartModel = require('../../../common/mysql/mapping/ItbCartModel');

var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var checkUtil = require('../util/checkUtil');
var printUtil = require('../util/printUtil');
var payUtil = require('../util/payUtil');
var usersUtil = require('../util/usersUtil');
var async = require('async');
var moment = require("moment");
//------------------app端 getOrderPrintParams_v5_2 模拟接口---------------------------
/**
 * 获取订单印刷参数(套餐)列表
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: tradeOrderId	商品订单 id
 * 返回值: {"success":1,"msg":"成功","data":{"printParams":[{"name":"套餐名称","id":996}]}}
 *
 * 测试地址: http://localhost:3000/v5/print/getOrderPrintParams_v5_2?device=1&userId=128685&tradeOrderId=1
 * */
// todo 模拟接口, 待实现, begin
function getOrderPrintParams_v5_2 (req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');

    if(userId == 0) {
        return printUtil.ret_func_json(0, 'userId 非法', {}, res);
    }
    if(tradeOrderId == 0) {
        return printUtil.ret_func_json(0, 'tradeOrderId 非法', {}, res);
    }

    //var data = {"printParams":[{"name":"套餐一","id":996},{"name":"套餐二","id":997},{"name":"套餐三","id":997}]};
    //return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);

    printUtil.getOrderPrintParams_v5_2(userId, tradeOrderId, function(error, data){
        if (error) {
            console.log('v5/print.js getOrderPrintParams_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {printParams:data||[]}, res);
    });

}
router.get('/getOrderPrintParams_v5_2', getOrderPrintParams_v5_2);
router.post('/getOrderPrintParams_v5_2', getOrderPrintParams_v5_2);
// todo 模拟接口, 待实现, end

//-------------------app 端 bindPrintParamToTradeOrder_v5_2 模拟接口------------------------------------
/**
 * 绑定套餐至商品订单
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid         设备唯一标识
 * 参数: userId       用户唯一标识
 * 参数: printParamId 套餐 id
 * 参数: tradeOrderId 商品订单 id
 * 测试地址: http://localhost:3000/v5/print/bindPrintParamToTradeOrder_v5_2?device=1&userId=128685&tradeOrderId=1&printParamId=1
 * */
// todo 模拟接口, 待实现, begin
function bindPrintParamToTradeOrder_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var printParamId = checkUtil.numberFromReq(req, 'printParamId');

    //if(userId == 0 || tradeOrderId == 0 || printParamId == 0) {
    //    return printUtil.ret_func_json(0, '参数错误', {}, res);
    //}
    //return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {}, res);

    printUtil.bindPrintParamToTradeOrder_v5_2(userId, tradeOrderId, printParamId, function(error, data){
        if (error) {
            console.log('v5/print.js bindPrintParamToTradeOrder_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });

}
router.get('/bindPrintParamToTradeOrder_v5_2', bindPrintParamToTradeOrder_v5_2);
router.post('/bindPrintParamToTradeOrder_v5_2', bindPrintParamToTradeOrder_v5_2);
// todo 模拟接口, 待实现, end
//-------------------app 端 getOrderAccessorys_v5_2 获取订单配件列表------------------------------------------
/**
 * 参数:device
 *      0 表示从pc来的请求
 *      1 表示ios
 *      2 表示android
 *      101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 *      3 标识app 嵌入网页
 *      4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: tradeOrderId	商品订单 id
 * 参数[废弃]: printParamId	 订单使用的印刷参数 id
 * 参数: pageNum
 * 参数: pageSize
 * 返回：data部分为：
 *      {
 *           "accessorys":[
 *               {
 *                   "id":996,
 *                   "name":"配件名称",
 *                   "desc":"门型展架",
 *                   "thumbs":[
 *                       "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"
 *                   ]
 *               }
 *           ]
 *       }
 *
 * 测试地址: http://localhost:3000/v5/print/getOrderAccessorys_v5_2?device=1&userId=128685&tradeOrderId=930
 * 注意: 	订单配件列表应固定一个配件: id 为 -1, 标识不使用配件
 * */
// todo 模拟接口, 待实现, begin
function getOrderAccessorys_v5_2 (req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var printParamId = checkUtil.numberFromReq(req, 'printParamId');
    if(userId == 0 || tradeOrderId == 0 ) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum');
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    //var data = {"success":1,"msg":"成功","data":{"accessorys":[{"id":996,"name":"配件名称","desc":"门型展架","thumbs":["http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"]},{"id":-1,"name":"无","desc":"门型展架","thumbs":["http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"]}]}};
    //return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    

    //var data = {"success":1,"msg":"成功","data":{"accessorys":[{"id":996,"name":"配件名称","desc":"门型展架","thumbs":["http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"]},{"id":-1,"name":"无","desc":"门型展架","thumbs":["http://itbour-back.oss-cn-hangzhou.aliyuncs.com/image/U13396/2017/01/18/123529924_qCMLw4bsRRcIJgyOwJxR.jpg"]}]}};
    printUtil.getOrderAccessorys(userId, tradeOrderId,printParamId, pageNum,pageSize, function(error,data){
        if(error){
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, data, res);
        }
        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });


}
router.get('/getOrderAccessorys_v5_2',getOrderAccessorys_v5_2);
router.post('/getOrderAccessorys_v5_2', getOrderAccessorys_v5_2);
// todo 模拟接口, 待实现, end

// -------------------app 端 bindAccessoryToTradeOrder_v5_2 模拟接口--------------------
/**
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数; accessoryId	配件 id
 * 参数: tradeOrderId	 商品订单 id
 *
 * 注意:	配件 id 传递 -1 时, 解绑配件, 标识不选则配件
 *
 * 测试地址: http://localhost:3000/v5/print/bindAccessoryToTradeOrder_v5_2?device=1&userId=128685&tradeOrderId=1&accessoryId=1
 * */
// todo 模拟接口, 待实现, begin
function bindAccessoryToTradeOrder_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var accessoryId = checkUtil.numberFromReq(req, 'accessoryId');
    if(userId == 0 || tradeOrderId == 0 || accessoryId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.bindAccessoryToTradeOrder_v5_2(userId, tradeOrderId, accessoryId, function (error, data) {
        if (error) {
            console.log('v5/print.js bindAccessoryToTradeOrder_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/bindAccessoryToTradeOrder_v5_2', bindAccessoryToTradeOrder_v5_2);
router.post('/bindAccessoryToTradeOrder_v5_2', bindAccessoryToTradeOrder_v5_2);
// todo 模拟接口, 待实现, end
//--------------------app 端 getOrderAccessoryCount_v5_2 获取订单配件数量列表
/**
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: tradeOrderId	商品订单 id
 * 参数(废弃): printParamId	订单使用的印刷参数 id
 * 参数(废弃): accessoryId	订单使用的配件 id
 *
 * 测试地址: http://localhost:3000/v5/print/getOrderAccessoryCount_v5_2?device=1&userId=128685&tradeOrderId=930
 * */
function getOrderAccessoryCount_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var accessoryId = checkUtil.numberFromReq(req, 'accessoryId');
    var printParamId = checkUtil.numberFromReq(req, 'printParamId');
    if(userId == 0 || tradeOrderId == 0 ) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    //var data = {"amount":[{"name":"1个","count":1},{"name":"3个","count":3}]};
    //return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);

    var defaultSize = 6
    printUtil.getOrderAccessoryCount(userId, tradeOrderId, defaultSize, function(error,data){
        if(error){
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, data, res);
        }
        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getOrderAccessoryCount_v5_2', getOrderAccessoryCount_v5_2);
router.post('/getOrderAccessoryCount_v5_2', getOrderAccessoryCount_v5_2);

//----------------app 端 modifyAccessoryCount_v5_2 模拟接口--------------------------
/**
 * 修改订单配件数量
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数; accessoryCount	配件数量
 * 参数: tradeOrderId	 商品订单 id
 *
 * 测试地址: http://localhost:3000/v5/print/modifyAccessoryCount_v5_2?device=1&userId=128685&tradeOrderId=1&accessoryCount=1
 * */
// todo 模拟接口, 待实现, begin
function modifyAccessoryCount_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var accessoryCount = checkUtil.numberFromReq(req, 'accessoryCount');
    if(userId == 0 || tradeOrderId == 0 || accessoryCount <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.modifyOrderAccessoryCount_v5_2(userId, tradeOrderId, accessoryCount, function (error, data) {
        if (error) {
            console.log('v5/print.js modifyAccessoryCount_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/modifyAccessoryCount_v5_2', modifyAccessoryCount_v5_2);
router.post('/modifyAccessoryCount_v5_2', modifyAccessoryCount_v5_2);
// todo 模拟接口, 待实现, end

//------------------ app 端 getOrderCoupons_v5_2 模拟接口--------------------------
/**
 * 获取当前订单的优惠券列表(可用/不可用)
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: tradeOrderId	 商品订单 id
 * 参数: conformOrder	0 标示获取订单不可使用的优惠券, 1 标示获取可订单可使用的优惠券
 * 注意: 绑定到当前订单的优惠券视为可用优惠券
 * 返回值:
 * {
    "success":1,
    "msg":"成功",
    "data":{
        "coupons":[
            {
                "id":986,
                "code":"QWERTPOIUYEV",
                "type_desc":"抵扣券",
                "discount_desc":"5.0元",
                "trade_type":20,
                "expiry_time":"2017-03-05",
                "coupon_desc":"暂不抵扣运费",
                "reason":""
            }
        ]
    }
 }
 * 测试地址: http://localhost:3000/v5/print/getOrderCoupons_v5_2?device=1&userId=128685&tradeOrderId=1&conformOrder=1
 * */
// todo 模拟接口, 待实现, begin
function getOrderCoupons_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var conformOrder = checkUtil.numberFromReq(req, 'conformOrder');
    if(userId == 0 || tradeOrderId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    printUtil.getOrderCoupons_v5_2(userId, tradeOrderId, conformOrder, function (error, data) {
        if (error) {
            console.log('v5/print.js getOrderCoupons_v5_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        // 获取1已绑定到当前订单的优惠券
        printUtil.getCouponInfoByTradeOrderId_v5_2(tradeOrderId, function(error1, coupon){
            if(error1) {
                console.log('v5/print.js getOrderCoupons_v5_2 Err 1: '+error1);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            coupon.expiry_time = moment(coupon.expiry_time).format('YYYY-MM-DD');
            // 订单没有绑定的优惠券无需处理
            if (!coupon || !coupon.id) {
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:data||[]}, res);
            }
            // 订单绑定有优惠券, 处理优惠券
            coupon = printUtil.genCouponRetInfo(coupon, userId, 0);

            var coupons = data || [];
            // 如果获取订单可用优惠券则添加当前优惠券
            if (conformOrder) {
                coupons.unshift(coupon); // 将当前订单绑定的优惠券放到第一个
                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:coupons}, res);
            }
            // 否则, 移除
            if(coupons.length > 0) {
                for(var i = 0; i < coupons.length; i++) {
                    var one = coupons[i];
                    // 一个订单只能绑定一个优惠券, 所以找到删除即可
                    if(one.id == coupon.id) {
                        coupons.splice(i, 1); break;
                    }
                }
            }
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {coupons:coupons}, res);
        })
    });
}
router.get('/getOrderCoupons_v5_2', getOrderCoupons_v5_2);
router.post('/getOrderCoupons_v5_2', getOrderCoupons_v5_2);
// todo 模拟接口, 待实现, end

//-----------------app 端 bindCouponToTradeOrder_v5_2  模拟接口---------------------
/**
 * 绑定/解绑优惠券至订单
 * 参数:device	"0 表示从pc来的请求
 * 1 表示ios
 * 2 表示android
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标识app 嵌入网页
 * 4 标识网站 web 端"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数; couponId	优惠券 id
 * 参数: tradeOrderId	 商品订单 id
 * 注意: 	"若订单已存在优惠券, 则先解绑优惠券再重新绑定
 *          若不使用优惠券则 传递 couponId 为 -1"
 * 测试地址: http://localhost:3000/v5/print/bindCouponToTradeOrder_v5_2?device=1&userId=128685&tradeOrderId=1&couponId=1
 * */
// todo 模拟接口, 待实现, begin
function bindCouponToTradeOrder_v5_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var tradeOrderId = checkUtil.numberFromReq(req, 'tradeOrderId');
    var couponId = checkUtil.numberFromReq(req, 'couponId');

    if(userId == 0 || tradeOrderId == 0 || couponId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.bindCouponToTradeOrder_v5_2(userId, tradeOrderId, couponId, function (error, data) {
        if (error) {
            console.log('v5/print.js bindCouponToTradeOrder_v5_2 Err: '+error);
            var errMsg = CODE.OPERATION_FAILED;
            if(typeof error === "string") {
                errMsg = error;
            }
            return printUtil.ret_func_json(0,errMsg,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{},res);
    });
}
router.get('/bindCouponToTradeOrder_v5_2', bindCouponToTradeOrder_v5_2);
router.post('/bindCouponToTradeOrder_v5_2', bindCouponToTradeOrder_v5_2);
// todo 模拟接口, 待实现, end

//-----------------------app 端 getPrintOrderInfo_v5_2 模拟接口
/**
 * 参数: device	"0表示从pc来的请求
 * 1表示ios
 * 2表示android
 * 101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 3 标示app 嵌入网页"
 * 参数: uuid	 设备唯一标识
 * 参数: userId	用户唯一标识
 * 参数: orderId	 订单唯一标识
 *
 * 原接口:  /print/getPrintOrderInfo
 *
 * 测试地址: http://localhost:3000/v5/print/getPrintOrderInfo_v5_2?device=1&userId=128685&orderId=1
 * */
// todo 模拟接口, 待实现, begin
function getPrintOrderInfo_v5_2 (req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(userId == 0 || orderId == 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    //var data = {"orderId":800,"orderNo":"51R31C1WQ5294","orderState":12,"addressInfo":{"id":679,"phone":13023456789,"name":"也一样","prov":{"id":150000,"text":"内蒙古自治区"},"city":{"id":150500,"text":"通辽市"},"dist":{"id":150522,"text":"科尔沁左翼后旗"},"detail":"也一样"},"productInfo":[{"id":345,"thumb":"http://oss-image.jpg","qty":2,"productFee":200,"title":"商品名","desc":"300G白卡亚模","price":100,"priceCount":2,"size":"A4大小(45x64)","unit":"张","printParaId":989,"detailOrderId":1,"printPara":{"id":989,"name":"套餐一","desc":"名片专用"}}],"accessoryInfo":[{"id":9,"count":2,"price":40,"accessoryFee":80,"desc":"门型展架"}],"couponInfo":{"id":986,"code":"QWERTPOIUYEV","type_desc":"抵扣券","discount_desc":"5.0元","trade_type":20,"expiry_time":"2017-03-05","coupon_desc":"暂不抵扣运费","reason":""},"totalDesignFee":0,"totalMailFee":0,"totalAccessoryFee":100,"totalFee":17400};

    // 串行获取数据
    async.series([
            function(callback){
                // 根据地址和数量计算子订单邮费、并更新总费用
                printUtil.calc_printOrderMailFee(orderId, function(error,data){ callback(error,data)});
            }, // *** 0
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            }, // *** 1
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            }, // *** 2
            function(callback){
                // 获取订单产品信息
                printUtil.get_tradeOrderDetailsInfo_v5_2(orderId, function(error,data){ callback(error,data)});
            }, // *** 3
            function(callback){
                printUtil.getCouponInfoByTradeOrderId_v5_2(orderId, function(error, data){callback(error,data)});
            }, // *** 4
            function(callback){
                printUtil.chkTradeOrderCanAddAccesstory_v5_2(orderId, function(error, data){callback(error,data)});
            }, // *** 5
            function(callback){
                printUtil.getOrderCouponsCnt_v5_2(userId, orderId, 1, function(error, data){callback(error,data)});
            } // *** 6
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            if(!results || results.length==0){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[2]){
                addressInfo = {
                    "id":results[2].addr_id,
                    "phone":results[2].mobile|| results[2].phone,
                    "mobile":results[2].mobile|| results[2].phone,
                    "name":results[2].name,
                    "prov":{"id":results[2].prov,"text":results[2].prov_name},
                    "city":{"id":results[2].city,"text":results[2].city_name},
                    "dist":{"id":results[2].dist,"text":results[2].dist_name},
                    "detail":results[2].detail
                };
            }


            // 总设计费和总运费
            var totalDesignFee = 0;
            var totalMailFee = 0;
            var totalAccesstoryFee = 0;
            for(var i=0;i<results[3].productInfo.length;i++){
                var one = results[3].productInfo[i];
                totalDesignFee += one.designFee;
                totalMailFee += one.mailFee;
            }
            for(var i=0;i<results[3].accesstoryInfo.length; i++){
                var one = results[3].accesstoryInfo[i];
                totalAccesstoryFee += one.accessoryFee;
                totalMailFee += one.mailFee;
            }

            var showAccessory = results[5] ? 1 : 0;

            // 如果当前订单绑定了优惠券, 则可用个数加一
            var couponsCnt = results[6];
            if(results[4] && results[4].id) {
                couponsCnt++;
            }

            var data = {
                "orderId":orderId,
                "orderNo":results[1].order_no,
                "orderState" : results[1].state,
                "addressInfo":addressInfo,
                "totalDesignFee":totalDesignFee,
                "totalMailFee":totalMailFee,
                "totalFee":results[1].total_fee,
                "productInfo":results[3].productInfo,
                "accessoryInfo":results[3].accesstoryInfo,
                "totalAccesstoryFee" : totalAccesstoryFee,
                "showAccessory" : showAccessory,
                "couponInfo" : results[4],
                "couponsCnt" : couponsCnt
            };
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
        });
}
router.get('/getPrintOrderInfo_v5_2', getPrintOrderInfo_v5_2);
router.post('/getPrintOrderInfo_v5_2', getPrintOrderInfo_v5_2);
// todo 模拟接口, 待实现, end


//============================== v5.5 START ==============================
/**
 * 3-1: 加入商品至购物车
 * 参数: device
 * 参数: userId
 * 参数: typeL: 商品标识 1 单页模板, 3 ppt 模板, 4 印品作品, 6 社交媒体模板
 * 参数: id: 添加商品的唯一标识(可能是模板, 可能是作品, 根据 typeL 区分)
 * 返回值:
 * {
 * 	"success" : 1,
 * 	"msg" : "成功",
 * 	"data" : {
 * 		"goodsCount" : 3
 * 	}
 * }
 */
function addGoodsToShopCart_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var typeL = checkUtil.numberFromReq(req, 'typeL');
    var id = checkUtil.numberFromReq(req, 'id');

    if(userId <= 0 || typeL <= 0 || id<=0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    (new ItbCartModel).getGoodsCntByUser(userId, function(getErr, cntInfo){
        if(getErr) {
            console.log('v5/print.js addGoodsToShopCart_v5_5 getGoodsCntByUser Err: '+getErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        // 检查购物车内当前商品数
        if(cntInfo && cntInfo.totalCnt>=0 && cntInfo.totalCnt<99) {
            // 加入购物车
            printUtil.addGoodsToShopCart_v5_5(userId, typeL, id, function (error, retData) {
                if (error) {
                    console.log('v5/print.js addGoodsToShopCart_v5_5 Err: '+error);
                    return printUtil.ret_func_json(0,error,{},res);// CODE.OPERATION_FAILED
                }

                return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
            });
        } else {
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
    });
}
router.get('/addGoodsToShopCart_v5_5', addGoodsToShopCart_v5_5);
router.post('/addGoodsToShopCart_v5_5', addGoodsToShopCart_v5_5);

/**
 * 3-2: 移除购物车商品
 * 参数: device
 * 参数: userId
 * 参数: ids: 购物车组合商品 id 数组的 json 字符串, 如: [382, 985]
 * 返回值:
 * {
 * 	"success" : 1,
 * 	"msg" : "成功",
 * 	"data" : {
 * 		"goodsCount" : 3
 * 	}
 * }
 */
function removeGoodsFromShopCart_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var arrIds = JSON.parse(checkUtil.stringFromReq(req, 'ids')||'[]');

    if(userId <= 0 || !arrIds || arrIds.length==0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.removeGoodsFromShopCart_v5_5(userId, arrIds, function (error, retData) {
        if (error) {
            console.log('v5/print.js removeGoodsFromShopCart_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        // 重新计算购物车商品整体数量价格信息
        printUtil.getUserShopCartCnt_v6_2(userId, null, function(getCartCntErr, cartCnt){
            if (getCartCntErr) {
                console.log('v5/print.js removeGoodsFromShopCart_v5_5 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            cartCnt.goodsCount = retData.goodsCount;
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,cartCnt,res);
        });
    });
}
router.get('/removeGoodsFromShopCart_v5_5', removeGoodsFromShopCart_v5_5);
router.post('/removeGoodsFromShopCart_v5_5', removeGoodsFromShopCart_v5_5);

/**
 * 3-3: 获取购物车商品列表
 * 参数: device
 * 参数: userId
 * 参数: pageNum
 * 参数: pageSize
 * 返回值:
 * {
 *  "success": 1,
 *  "msg": "成功",
 *  "data": {
 *    "shopCart": {
 *      "totalCount": 23,
 *      "selectCount": 13,
 *      "selectTotalFee" : 3200
 *    },
 *    "goodsList": [
 *      {
 *        "id": 985,  // 组合商品 id
 *        "itemId": 123,
 *        "thumbs": "http://oss-images-1.jpg",
 *        "itemParam": {"ppId": 211,"title": "套餐一","desc": "白卡亚模"},
 *        "itemCnt": {
 *          "price": 9,
 *          "show": 2,
 *          "unit": "盒"
 *        },
 *        "assyList": [
 *          {
 *            "itemId":124,
 *            "assyParam": {"ppId": 212,"title": "门型展架","desc": "铝合金"},
 *            "assyCnt": {
 *              "price": 9,
 *              "show": 2,
 *              "unit": "盒"
 *            }
 *          }
 *        ],
 *        "selected": 1,
 *        "designFee": 0,
 *        "totalFee": 989
 *      }
 *    ]
 *  }
 * }
 * 测试地址: http://localhost:3000/v5/print/getShopCartGoodsList_v5_5?userId=299174&pageNum=0&pageSize=100
 */
function getShopCartGoodsList_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    if(pageSize <= 0) {
        pageSize = 12;// 默认值
    }

    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getShopCartGoodsList_v5_5(userId, pageNum, pageSize, function (error, retData) {
        if (error) {
            console.log('v5/print.js getShopCartGoodsList_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getShopCartGoodsList_v5_5', getShopCartGoodsList_v5_5);
router.post('/getShopCartGoodsList_v5_5', getShopCartGoodsList_v5_5);

/**
 * 3-4: 获取购物车内某商品参数列表
 * 参数: device
 * 参数: userId
 * 参数: goodsId  组合商品id
 * 返回值:
 * {
 *   "success":1,
 *   "msg":"成功",
 *   "data":{
 *       "cur":{// 当前选择的套餐/数量
 *           "curItem":{
 *               "itemId":999,
 *               "ppId":3,
 *               "cnt":5
 *           },
 *           "curAssy":[
 *               {
 *                   "itemId":988,
 *                   "ppId":1,
 *                   "cnt":1
 *               }
 *           ],
 *           "designFee":0,
 *           "totalFee":33
 *       },
 *       "itemList":[// 商品/配件数据源
 *           {
 *               "itemId":999,
 *               "itemParams":[
 *                   {
 *                       "ppId":211,
 *                       "title":"套餐一",
 *                       "desc":"白卡亚模",
 *                       "pricing":10,
 *                       "qty":[
 *                           {
 *                               "maxCount":10,
 *                               "minCount":2,
 *                               "price":10,
 *                               "show":2,
 *                               "unit":"盒"
 *                           }
 *                       ],
 *                       "size":{
 *                           "desc":"A4大小",
 *                           "height":480,
 *                           "unit":"mm",
 *                           "width":320
 *                       },
 *                       "assyIds":[// 当前商品关联配件的商品 id 的二维数组
 *                           [23,46],
 *                           [23,46]
 *                       ]
 *                   }
 *               ]
 *           },
 *           {
 *               "itemId":997,
 *               "itemParams":[
 *                   {
 *                       "ppId":211,
 *                       "title":"套餐一",
 *                       "desc":"白卡亚模",
 *                       "pricing":10,
 *                       "qty":[
 *                           {
 *                               "maxCount":10,
 *                               "minCount":2,
 *                               "price":10,
 *                               "show":2,
 *                               "unit":"盒"
 *                           }
 *                       ],
 *                       "size":{
 *                           "desc":"A4大小",
 *                           "height":480,
 *                           "unit":"mm",
 *                           "width":320
 *                       },
 *                       "assyIds":[
 *                       ]
 *                   }
 *               ]
 *           }
 *       ]
 *   }
 * }
 *
 * 测试地址: http://localhost:3000/v5/print/getShopCartGoodsParams_v5_5?deivce=1&userId=299174&goodsId=1585
 */
function getShopCartGoodsParams_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var goodsId = checkUtil.numberFromReq(req, 'goodsId')||0;
    if(userId <= 0 || goodsId<=0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getShopCartGoodsParams_v5_5(userId, goodsId, function (error, retData) {
        if (error) {
            console.log('v5/print.js getShopCartGoodsParams_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getShopCartGoodsParams_v5_5', getShopCartGoodsParams_v5_5);
router.post('/getShopCartGoodsParams_v5_5', getShopCartGoodsParams_v5_5);

/**
 * 3-5: 修改购物车内某商品参数
 * 参数: device
 * 参数: userId:  用户id
 * 参数: goodsId:  组合商品 id
 * 参数: params:  json 字符串
 * {
 *  "curItem": {
 *    "itemId": 999,
 *    "ppId": 3,
 *    "cnt": 5
 *  },
 *  "curAssy": [
 *    {
 *     "itemId": 988,
 *     "ppId": 1,
 *     "cnt": 1
 *    }
 *  ],
 *  "selected": 1
 * }
 */
function modifyShopCartGoodsParams_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var goodsId = checkUtil.numberFromReq(req, 'goodsId')||0;
    var params = JSON.parse(checkUtil.stringFromReq(req, 'params')||'{}');

    if(userId <= 0 || goodsId<=0 || !params || !params.curItem || !params.curItem.itemId) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.modifyShopCartGoodsParams_v5_5(userId, goodsId, params, function (error, retData) {
        if (error) {
            console.log('v5/print.js modifyShopCartGoodsParams_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        // 重新计算购物车商品整体数量价格信息
        printUtil.getUserShopCartCnt_v6_2(userId, goodsId, function(getCartCntErr, cartCnt){
            if (getCartCntErr) {
                console.log('v5/print.js modifyShopCartGoodsParams_v5_5 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,cartCnt,res);
        });
    });
}
router.get('/modifyShopCartGoodsParams_v5_5', modifyShopCartGoodsParams_v5_5);
router.post('/modifyShopCartGoodsParams_v5_5', modifyShopCartGoodsParams_v5_5);

/**
 * 3-6: 预结算购物车内选中的商品(确认订单)
 * 参数: device
 * 参数: userId
 * 参数[可选]: couponId
 * 参数[可选]: mailType: 10预付邮费[默认], 20到付邮费
 * 返回值:
 */
function getPrePayOrderInfo_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    var mailType = checkUtil.numberFromReq(req, 'mailType')||10;
    if(userId <= 0 || device<0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getPrePayOrderInfo_v5_5(userId, couponId, mailType, function (error, retData) {
        if (error) {
            console.log('v5/print.js getPrePayOrderInfo_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getPrePayOrderInfo_v5_5', getPrePayOrderInfo_v5_5);
router.post('/getPrePayOrderInfo_v5_5', getPrePayOrderInfo_v5_5);

/**
 * 3-7: 获取购物车/订单商品列表
 * 参数: device
 * 参数: userId
 * 参数[可选]: orderId:  商品订单 id, 如不传, 则返回购物车内选中的商品列表
 * 参数: pageNum
 * 参数: pageSize
 * 返回值:
 * (结构和[接口3-10]中的[detailItems]类似)
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "goodsList": [
 *     {
 *       "id": 985, // 组合商品 id
 *       "itemId": 999, // 商品 id
 *       "productId:" 123, // 用户作品id
 *       "thumbs": "http://oss-images-1.jpg",
 *       "title": "商品名",
 *       "detailOrderId": 988,
 *       "itemParam": {
 *         "ppId": 211,
 *         "title": "套餐一",
 *         "desc": "白卡亚模"
 *       },
 *       "itemCnt": {
 *         "maxCount": 20,
 *         "minCount": 11,
 *         "price": 9,
 *         "show": 2,
 *         "unit": "盒"
 *       },
 *       "assyList": [ // 组合商品对应配件列表
 *         {
 *           "id": 878,
 *           "itemId": 999,
 *           "assyCnt": {
 *             "maxCount": 20,
 *             "minCount": 11,
 *             "price": 9,
 *             "show": 2,
 *             "unit": "盒"
 *           },
 *           "assyParam": {
 *             "ppId": 212,
 *             "title": "门型展架",
 *             "desc": "铝合金"
 *           }
 *         }
 *       ],
 *       "itemFee": 20,
 *       "assyFee": 80,
 *       "designFee": 0,
 *       "totalFee": 100
 *     }
 *   ]
 *  }
 * }
 */
function getOrderGoodsList_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var orderId = checkUtil.numberFromReq(req, 'orderId')||0;

    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;

    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getOrderGoodsList_v5_5(userId, orderId, pageNum, pageSize, function (error, retData) {
        if (error) {
            console.log('v5/print.js getOrderGoodsList_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {goodsList:retData}, res);
    });
}
router.get('/getOrderGoodsList_v5_5', getOrderGoodsList_v5_5);
router.post('/getOrderGoodsList_v5_5', getOrderGoodsList_v5_5);

/**
 * 3-8: 获取购物车内商品优惠券列表(可用/不可用)
 * 参数: device
 * 参数: userId
 * 参数: flg:  0 标示获取不可使用的优惠券, 1 标示获取可使用的优惠券
 * 返回值:
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "coupons": [
 *     {
 *       "id": 986,
 *       "code": "QWERTPOIUYEV",
 *       "type_desc": "抵扣券",
 *       "discount_desc": "5.0元",
 *       "trade_type": 20,
 *       "expiry_time": "2017-03-05",
 *       "coupon_desc": "暂不抵扣运费",
 *       "reason": "",
 *       "limit_type": 4
 *     }
 *   ]
 *  }
 * }
 */
function getShopCartCoupons_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var flg = checkUtil.numberFromReq(req, 'flg')||0;
    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getShopCartCoupons_v5_5(userId, flg, function (error, retData) {
        if (error) {
            console.log('v5/print.js getShopCartCoupons_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{coupons:retData},res);
    });
}
router.get('/getShopCartCoupons_v5_5', getShopCartCoupons_v5_5);
router.post('/getShopCartCoupons_v5_5', getShopCartCoupons_v5_5);

/**
 * 3-9: 获取用户商品订单列表
 * 参数: device
 * 参数: userId
 * 参数(可选): states: 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
 *                    所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
 * 参数: pageNum
 * 参数: pageSize
 * 返回值:
 * detailItems 为子商品订单 id, 配件应过滤, 归属于商品子订单
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": [
 *     {
 *       "orderId": 123456789,
 *       "orderNo": "QGFTNNKKDLLJ",
 *       "state": 70,
 *       "totalFee": 300,
 *       "detailItems": [
 *         {
 *           "detailOrderId": 988,
 *           "productId": 1234,
 *           "thumb": "http://oss-image-thumb.jpg"
 *         }
 *       ],
 *       "additionalInfo": {
 *         "createTime": "2016-10-16",
 *         "payTime": "2016-12-1815:03",
 *         "printTime": "2016-12-1815:03",
 *         "mailTime": "2016-12-1815:03",
 *         "doneTime": "2016-12-1815:03",
 *         "countdownPay": "23小时后交易自动关闭",
 *         "countdownDone": "5天后交易自动关闭"
 *       }
 *     }
 *   ]
 * }
 * 测试地址: http://localhost:3000/v5/print/getUserOrderList_v5_5?device=1&userId=128685
 */
function getUserOrderList_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var states = JSON.parse(checkUtil.stringFromReq(req, 'states')||'[]');

    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    if(pageSize <= 0) {
        pageSize = 12;// 默认值
    }

    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getUserOrderList_v5_5(userId, states, pageNum, pageSize, function (error, retData) {
        if (error) {
            console.log('v5/print.js getUserOrderList_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getUserOrderList_v5_5', getUserOrderList_v5_5);
router.post('/getUserOrderList_v5_5', getUserOrderList_v5_5);

/**
 * 3-9: 获取用户商品订单列表
 * 参数: device
 * 参数: userId
 * 参数(可选): states: 订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消
 *                    所需订单状态数组, 如[10, 30]，如果不传则返回全部状态订单
 * 参数: pageNum
 * 参数: pageSize
 * 返回值:
 * detailItems 为子商品订单 id, 配件应过滤, 归属于商品子订单
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "list": [
 *     {
 *       "orderId": 123456789,
 *       "orderNo": "QGFTNNKKDLLJ",
 *       "state": 70,
 *       "totalFee": 300,
 *       "detailItems": [
 *         {
 *           "detailOrderId": 988,
 *           "productId": 1234,
 *           "thumb": "http://oss-image-thumb.jpg"
 *         }
 *       ],
 *       "additionalInfo": {
 *         "createTime": "2016-10-16",
 *         "payTime": "2016-12-1815:03",
 *         "printTime": "2016-12-1815:03",
 *         "mailTime": "2016-12-1815:03",
 *         "doneTime": "2016-12-1815:03",
 *         "countdownPay": "23小时后交易自动关闭",
 *         "countdownDone": "5天后交易自动关闭"
 *       }
 *     }
 *   ]
 *  }
 * }
 * 测试地址: http://localhost:3000/v5/print/getUserOrderList_v6_1?device=1&userId=299174&withTotalPage=1
 */
function getUserOrderList_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var states = JSON.parse(checkUtil.stringFromReq(req, 'states')||'[]');
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage') || 0;

    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    if(pageSize <= 0) {
        pageSize = 12;// 默认值
    }

    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getUserOrderList_v5_5(userId, states, pageNum, pageSize, function (error, retData) {
        if (error) {
            console.log('v5/print.js getUserOrderList_v6_1 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        var data = {list : retData};
        if(!withTotalPage) {
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
        }
        // 获取总页数
        printUtil.getPrintOrderListCnt(userId, states, function(err, cnt){
            if(err) {
                console.log('v5/print.js getUserOrderList_v6_1 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            data.totalPage = Math.floor((cnt-1)/pageSize)+1;
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
        });
    });
}
router.get('/getUserOrderList_v6_1', getUserOrderList_v6_1);
router.post('/getUserOrderList_v6_1', getUserOrderList_v6_1);

/**
 * 3-10: 获取用户订单详情信息
 * 参数: device
 * 参数: userId   用户唯一标识
 * 参数: orderId  商品订单 唯一标识
 * 参考旧接口: /print/getOrderDetail
 *   新增项目: "assyList":[{"id":878,"itemId":999,"assyCnt":{"maxCount":20,"minCount":11,"price":9,"show":2,"unit":"盒"},"assyParam":{"ppId":212,"title":"门型展架","desc":"铝合金"}}],
 *   测试地址: http://localhost:3000/v5/print/getPrintDetail_v5_5?device=1&userId=299174&orderId=904
 */
function getPrintDetail_v5_5(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    if(!orderId) {
        return printUtil.ret_func_json(0,CODE.ORDER_ID_EMPTY,{},res);
    }

    // 串行获取数据
    async.series([
            function(callback){
                // 获取订单基本信息
                printUtil.get_printOrderBaseInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***0
            function(callback){
                // 获取订单地址
                printUtil.get_printAddressInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***1
            function(callback){
                // 获取订单产品信息
                //printUtil.get_printProductInfo(orderId, function(error,data){ callback(error,data)});
                callback(null,null);
            }, // ***2
            function(callback){
                // 获取订单附加信息
                printUtil.get_additionalInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***3
            function(callback){
                printUtil.get_logisticsInfo(orderId, function (err, data) {callback(err,data);});
            }, // ***4
            function(callback){
                // 获取订单快递公司信息
                printUtil.get_deliveryInfo(orderId, function(error,data){ callback(error,data)});
            }, // ***5
            function(callback){
                // 获取子订单信息 (按组合商品分组)
                printUtil.get_printProductInfo_v5_5(orderId, function(error,data){callback(error,data)})
            }, // ***6
            function(callback){
                printUtil.getCouponInfoByTradeOrderId_v5_2(orderId, function(error,data){callback(error,data)})
            }, // ***7
            function(callback) {
                printUtil.chkOrderIsSeckillOrder(orderId,function(error,data){callback(error,data)});
            } // ***8
        ],

        function(err, results){
            if(err){
                console.log(err);
                return printUtil.ret_func_json(0,'error',{},res);
            }
            if(!results || results.length==0 || !results[0] || !results[6]){
                return printUtil.ret_func_json(0,'error',{},res);
            }

            // 地址
            var addressInfo =  null;
            if(results[1]){
                addressInfo = {
                    "id":results[1].addr_id,
                    "phone":results[1].mobile|| results[1].phone,
                    "mobile":results[1].mobile|| results[1].phone,
                    "name":results[1].name,
                    "prov":{"id":results[1].prov,"text":results[1].prov_name},
                    "city":{"id":results[1].city,"text":results[1].city_name},
                    "dist":{"id":results[1].dist,"text":results[1].dist_name},
                    "detail":results[1].detail
                };
            }

            // 子订单消息
            var detailItems = [];
            // 费用
            var totalProductFee = 0;
            var totalDesignFee = 0;
            var totalMailFee = 0;
            var totalAssyFee = 0;

            for(var i=0;i<results[6].length;i++){
                // 主商品
                var one = results[6][i];
                totalProductFee += one.product_fee;
                totalDesignFee += one.design_fee;
                totalMailFee += one.mail_fee;

                // 附件
                var assyList = [];
                var assyFee = 0;
                if(one.assyList && one.assyList.length>0) {
                    for(var j=0;j<one.assyList.length;j++){
                        var assy = one.assyList[j];
                        totalAssyFee += assy.product_fee;
                        totalProductFee += assy.product_fee;
                        totalMailFee += assy.mail_fee;
                        assyFee += assy.product_fee;

                        assyList.push({
                            id: assy.detail_id,
                            itemId: assy.item_id,
                            title: assy.item_name,
                            assyParam: {
                                ppId: assy.pp_id,
                                title: assy.pp_name,
                                desc: assy.pp_desc,
                            },
                            assyCnt: {
                                maxCount: assy.qty_max,
                                minCount: assy.qty_min,
                                price: assy.product_fee,// TODO
                                show: assy.qty,
                                unit: assy.qty_unit
                            }
                        });
                    }
                }

                detailItems.push({
                    id: one.detail_id,
                    itemId: one.item_id,
                    productId: one.user_doc_id,
                    thumb: one.thumb,
                    itemThumb : one.item_thumb,  // add 2017-08-17 by wangjun 增加商品图返回
                    title: one.item_name,
                    itemFee: one.product_fee,
                    assyFee: assyFee,
                    designFee: one.design_fee,
                    totalFee: one.product_fee+assyFee+one.design_fee,// 除去邮费
                    itemParam: {
                        ppId: one.pp_id,
                        title: one.pp_name,
                        desc: one.pp_desc,
                    },
                    itemCnt: {
                        maxCount: one.qty_max,
                        minCount: one.qty_min,
                        price: one.product_fee,// TODO
                        show: one.qty,
                        unit: one.qty_unit
                    },
                    assyList: assyList,
                });
            }

            var feeInfo = {
                productFee: totalProductFee+totalDesignFee,
                mailFee: totalMailFee,
                mailType: results[0].express_type,// added 2017-06-27
                couponFee: results[0].coupon_fee,
                totalFee: results[0].total_fee
            };

            //物流信息
            var logisticsInfo = [];
            if(results[4] && results[4].length>0){
                logisticsInfo.push(results[4][0]);
            }

            var retData = {
                "orderId": orderId,
                "orderNo": results[0].order_no,
                "state": results[0].state,
                "addressInfo": addressInfo,
                "detailItems": detailItems,
                "couponInfo": results[7],
                "additionalInfo": results[3],
                "logisticsInfo": logisticsInfo,
                "deliveryInfo": results[5],
                "feeInfo": feeInfo,
                "kind" : results[8]
            };

            return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, retData, res);
        });
}
router.get('/getPrintDetail_v5_5', getPrintDetail_v5_5);
router.get('/getPrintDetail_v5_5', getPrintDetail_v5_5);

/**
 * 3-11: 获取购物车支付参数(结算)
 * 参数: device
 * 参数: userId
 * 参数: couponId: 优惠券, 若没有, 传递 -1
 * 参数[可选]: mailType: 10预付邮费[默认], 20到付邮费
 * 返回值:
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "orderId" : 981,
 *   "orderNo" : "ASDFGHJKL",
 *   "prepayId": 789,
 *   "nonceStr": "qwertyuiopsdfghjkl",
 *   "timeStamp": 999990909090,
 *   "sign": "QWKSJDFHGJHDFHHDHH"
 *  }
 * }
 * 注意:
 * 1.地址来源用用户最新地址的拷贝
 * 2.商品来源于购物车已选中的商品
 * 3.优惠券来源于接口传递的优惠券 id
 * 4.后台需先创建订单, 将购物车选中商品从购物车移除
 * 5.绑定优惠券, 然后发起支付
 */
function createOrderAndPay_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    var mailType = checkUtil.numberFromReq(req, 'mailType')||10;
    if(device<0 || userId <=0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    // 创建订单
    //printUtil.createOrderFromCart_v5_5(device, userId, couponId, function (crtErr, crtOrderInfo) {
    printUtil.createOrderFromCart_2_v5_5(device, userId, couponId, mailType, function (crtErr, crtOrderInfo) {
        if (crtErr) {
            console.log('v5/print.js createOrderFromCart_v5_5 Err: '+crtErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(crtOrderInfo && crtOrderInfo.orderId>0) {
            // 将选中商品从购物车删除
            printUtil.removeSelectedGoodsFromShopCart_v5_5(userId, function(delErr, delRet){
                if(delErr) {
                    return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                // 调用微信支付
                payUtil.getUnifiedOrder(device, userId, null, crtOrderInfo.orderId, 10, function(getErr, getRet){
                    if(getErr){
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    var data = {
                        orderId: crtOrderInfo.orderId,
                        orderNo: crtOrderInfo.orderNo,
                        prepayId: '',
                        nonceStr: '',
                        timeStamp: '',
                        sign: ''
                    };
                    if(getRet) {
                        data.prepayId = getRet.prepayId||'';
                        data.nonceStr = getRet.nonceStr||'';
                        data.timeStamp = getRet.timeStamp||'';
                        data.sign = getRet.sign||'';
                    }
                    return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
                });
            });

        } else {
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
    });
}
router.get('/createOrderAndPay_v5_5', createOrderAndPay_v5_5);
router.post('/createOrderAndPay_v5_5', createOrderAndPay_v5_5);

/**
 * 3-12: 设置商品选中状态
 * 参数: device
 * 参数: userId
 * 参数: selected:  0, 标识不选中, 1, 标记选中
 * 参数: goodsId:  组合商品 id (设置时, 若存在配件需要将配件也选中), -1时表示操作所有商品
 * 返回值:
 */
function setShopCartGoodsSelect_v5_5(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var goodsId = checkUtil.numberFromReq(req, 'goodsId')||0;
    var selected = checkUtil.numberFromReq(req, 'selected')||0;
    if(userId <= 0 || goodsId==0 || selected<0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.setShopCartGoodsSelect_v5_5(userId, goodsId, selected, function (error, retData) {
        if (error) {
            console.log('v5/print.js setShopCartGoodsSelect_v5_5 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        // 重新计算购物车商品整体数量价格信息
        printUtil.getUserShopCartCnt_v6_2(userId, goodsId, function(getCartCntErr, cartCnt){
            if (getCartCntErr) {
                console.log('v5/print.js setShopCartGoodsSelect_v5_5 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,cartCnt,res);
        });
    });
}
router.get('/setShopCartGoodsSelect_v5_5', setShopCartGoodsSelect_v5_5);
router.post('/setShopCartGoodsSelect_v5_5', setShopCartGoodsSelect_v5_5);

//============================== v5.5 END ==============================

//============================== v5.6 START ==============================
/**
 * 5-15: 获取场景案例列表
 * /v5/print/getScenceList_v5_6
 *  参数: device
 *  参数: pageNum    请求页
 *  参数: pageSize    请求页大小
 *  参数[可选]: withTotalPage    是否需要总页数
 {
   "success": 1,
   "msg": "成功",
   "data": {
     "column": 1,
     "lsit": [
       {
         "h": 204,
         "w": 344,
         "id": 982,
         "thumb": "http://itbourgenerate.osscnhangzhou.aliyuncs.com/image/0.jpg",
         "url" : "http://www.itbour.com/scene/yi-jia-si-shi-nian-de-lao-dian.html",
         "title": "一家四十年的老店",
         "desc" : "浦沿*新生村....."
       }
     ]
   }
 }

 */
function getScenceList_v5_6(req, res, next) {

    var pageNum = Number(req.query.pageNum || req.body.pageNum || '0');
    var pageSize = Number(req.query.pageSize || req.body.pageSize || '12');
    var device = checkUtil.numberFromReq(req, 'device');

    printUtil.getScenceList_v5_6(pageNum, pageSize, device,function (error, data) {
        if (error) {
            console.log('print.js getScenceList_v5_6 Err: ' + error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED, {}, res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS, {column: 1, list: data}, res);
    });
}
router.get('/getScenceList_v5_6', getScenceList_v5_6);
router.post('/getScenceList_v5_6', getScenceList_v5_6);

/**
 * 获取印品列表
 * 参数: device	 0表示从pc来的请求1表示ios/2表示android/3标示app 嵌入网页/101表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 参数: uuid	 设备唯一标识
 * 参数: userId	 用户唯一标识
 * 参数: typeM	 二级分类   40100: 名片  40200: 传单
 * 参数: typeL    一级分类    0 未分类   1 海报  2 多页  3 ppt.  4. 印品
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 *
 * 返回:
 * {"success":1,
 *  "msg":"成功",
 *  "data":{
 *      "column": 2,
 *      "list":[
 *          {
 *              "id":123
 *              "thumb":"http://itbour-generate.img-cn-hangzhou.aliyuncs.com/image/U11/2016/11/22/102001731_xVhZWGl89XZlgzubQIkZ/0.jpg",
 *              "title":"xx蓝色商务",
 *              "price":"7元/盒 起",
 *              "useCount":999,
 *              "w":334,
 *              "h":256
 *          }
 *      ]
 *   }
 * }
 * */
function getPrintItemsList_v5_6(req, res, next) {
    var device = checkUtil.stringFromReq(req, 'device');
    if(!device) {
        return printUtil.ret_func_json(0,CODE.DEVICE_EMPTY,{},res);
    }
    var uuid = checkUtil.stringFromReq(req, 'uuid');
    if(!uuid) {
        return printUtil.ret_func_json(0,CODE.UUID_EMPTY,{},res);
    }
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(!userId) {
        return printUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    var typeM = checkUtil.numberFromReq(req, 'typeM');
    if(!typeM) {
        return printUtil.ret_func_json(0,CODE.TYPE_M_EMPTY,{},res);
    }
    var typeL = checkUtil.numberFromReq(req, 'typeL');
    if(!typeL) {
        return printUtil.ret_func_json(0,CODE.TYPE_L_EMPTY,{},res);
    }
    var pageNum = checkUtil.numberFromReq(req, 'pageNum') || 0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize') || 12;
    printUtil.getPrintItemsList_v5_6(typeM, pageNum, pageSize, function(error, ret){
        if(error){
            console.log(error);
            return printUtil.ret_func_json(0, CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1, CODE.OPERATION_SUCCESS,ret,res);
    });
};
router.get('/getPrintItemsList_v5_6', getPrintItemsList_v5_6);
router.post('/getPrintItemsList_v5_6', getPrintItemsList_v5_6);
//============================== v5.6 END ==============================

// -----------------------------------------------------------------------
/**
 * 预结算用户购物车选中商品
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3 标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数[可选]: couponId	 优惠券 id, 若传递需加上优惠券进行合计计算
 * 参数: mailType	邮费类型,10 预付邮费, 20 到付邮费
 * 参数[可选]: addressId	地址 id, 默认为用户最新地址
 *
 * 测试地址: http://localhost:3000/v5/print/getPrePayOrderInfo_v5_7?device=1&userId=299188&couponId=-1&mailType=10&addressId=-1
 * */
function getPrePayOrderInfo_v5_7(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    var mailType = checkUtil.numberFromReq(req, 'mailType')||10;
    var addressId = checkUtil.numberFromReq(req, "addressId") || -1;
    if(userId <= 0 || device<0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    couponId = couponId <= 0 ? 0 : couponId;
    // 先获取地址
    usersUtil.getUserAddressIdForSettlement_v5_7(userId, addressId, function(addrErr, addrId){
        if (addrErr) {
            console.log('v5/print.js [getPrePayOrderInfo_v5_7] getUserAddressIdForSettlement_v5_7 Err: '+addrErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        printUtil.getPrePayOrderInfo_v5_7(userId, couponId, mailType, addrId,function (error, retData) {
            if (error) {
                console.log('v5/print.js getPrePayOrderInfo_v5_5 Err: '+error);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }

            return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
        });
    });

}
router.get('/getPrePayOrderInfo_v5_7', getPrePayOrderInfo_v5_7);
router.post('/getPrePayOrderInfo_v5_7', getPrePayOrderInfo_v5_7);

//------------------------------------------------------------------------------------------------
/**
 * 获取用户购物车支付参数
 *
 * 参数:device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3 标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: couponId	优惠券, 若没有, 传递 -1
 * 参数[可选]: mailType	邮费计算类型, 10 预付邮费, 20 到付邮费, 默认为10, 预支付邮费
 * 参数[可选]: addressId	下单地址, 默认为用户的最新地址
 *
 * 测试地址: http://localhost:3000/v5/print/createOrderAndPay_v5_7?device=1&userId=299188&couponId=-1&mailType=10&addressId=3564
 * */
function createOrderAndPay_v5_7(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    var mailType = checkUtil.numberFromReq(req, 'mailType')||10;
    var addressId = checkUtil.numberFromReq(req, "addressId") || -1;
    if(userId <= 0 || device<0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    couponId = couponId <= 0 ? 0 : couponId;
    addressId = addressId <= 0 ? 0: addressId;
    // 先获取地址
    usersUtil.getUserAddressIdForSettlement_v5_7(userId, addressId, function(addrErr, addrId){
        if (addrErr) {
            console.log('v5/print.js [createOrderAndPay_v5_7] getUserAddressIdForSettlement_v5_7 Err: '+addrErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(addrId <= 0) {
            return printUtil.ret_func_json(0, '参数错误', {}, res);
        }
        // 根据购物车创建订单
        printUtil.createOrderFromCart_2_v5_7(device, userId, couponId, mailType, addrId, function (crtErr, crtOrderInfo) {
            if (crtErr) {
                console.log('v5/print.js createOrderFromCart_v5_5 Err: '+crtErr);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }

            if(crtOrderInfo && crtOrderInfo.orderId>0) {
                // 将选中商品从购物车删除
                printUtil.removeSelectedGoodsFromShopCart_v5_5(userId, function(delErr, delRet){
                    if(delErr) {
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    // 调用微信支付
                    payUtil.getUnifiedOrder(device, userId, null, crtOrderInfo.orderId, 10, function(getErr, getRet){
                        if(getErr){
                            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                        }

                        var data = {
                            orderId: crtOrderInfo.orderId,
                            orderNo: crtOrderInfo.orderNo,
                            prepayId: '',
                            nonceStr: '',
                            timeStamp: '',
                            sign: ''
                        };
                        if(getRet) {
                            data.prepayId = getRet.prepayId||'';
                            data.nonceStr = getRet.nonceStr||'';
                            data.timeStamp = getRet.timeStamp||'';
                            data.sign = getRet.sign||'';
                        }
                        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
                    });
                });

            } else {
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
        });

    });
}
router.get('/createOrderAndPay_v5_7', createOrderAndPay_v5_7);
router.post('/createOrderAndPay_v5_7', createOrderAndPay_v5_7);

//------------------------------------------------------------------------------------------------
/**
 * 获取用户购物车支付参数(网页端)
 *
 * 参数: device
 * 参数: userId	用户唯一标识
 * 参数: couponId	优惠券, 若没有, 传递 -1
 * 参数[可选]: mailType	邮费计算类型, 10 预付邮费, 20 到付邮费, (默认为10, 预支付邮费)
 * 参数[可选]: addressId	下单地址, 默认为用户的最新地址
 *
 * * */
function createOrderAndPayForWeb_v6_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    var mailType = checkUtil.numberFromReq(req, 'mailType')||10;
    var addressId = checkUtil.numberFromReq(req, "addressId") || -1;
    if(userId <= 0 || device<0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }
    couponId = couponId <= 0 ? 0 : couponId;
    addressId = addressId <= 0 ? 0: addressId;
    // 先获取地址
    usersUtil.getUserAddressIdForSettlement_v5_7(userId, addressId, function(addrErr, addrId){
        if (addrErr) {
            console.log('v5/print.js [createOrderAndPayForWeb_v6_2] getUserAddressIdForSettlement_v5_7 Err: '+addrErr);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(addrId <= 0) {
            return printUtil.ret_func_json(0, '参数错误', {}, res);
        }
        // 根据购物车创建订单
        printUtil.createOrderFromCart_2_v5_7(device, userId, couponId, mailType, addrId, function (crtErr, crtOrderInfo) {
            if (crtErr) {
                console.log('v5/print.js [createOrderAndPayForWeb_v6_2] createOrderFromCart_2_v5_7 Err: '+crtErr);
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }

            if(crtOrderInfo && crtOrderInfo.orderId>0) {
                // 将选中商品从购物车删除
                printUtil.removeSelectedGoodsFromShopCart_v5_5(userId, function(delErr, delRet){
                    if(delErr) {
                        return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    // 调用微信支付
                    payUtil.getUnifiedOrderWeb(device, userId, crtOrderInfo.orderId, 10, function(getErr, getRet){
                        if(getErr){
                            console.log('v5/print.js [createOrderAndPayForWeb_v6_2] getUnifiedOrderWeb Err: '+getErr);
                            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                        }

                        var data = {
                            orderId: crtOrderInfo.orderId,
                            orderNo: crtOrderInfo.orderNo,
                            prepay_id: '',
                            code_url: ''
                        };
                        if(getRet) {
                            data.prepay_id = getRet.prepay_id||'';
                            data.code_url = getRet.code_url||'';
                        }
                        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,data,res);
                    });
                });

            } else {
                return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
            }
        });

    });
}
router.get('/createOrderAndPayForWeb_v6_2', createOrderAndPayForWeb_v6_2);
router.post('/createOrderAndPayForWeb_v6_2', createOrderAndPayForWeb_v6_2);

//----------------------------------------------------------------------
/**
 * 3-34: 获取预支付 vip 订单信息
 * 参数: device
 * 参数: userId
 * 参数: itemId 虚拟商品id
 * 参数[可选]: couponId
 * 注意: 后台可在此接口加入判断是否有未完成的订单, 并进行后续处理
 * 返回值:
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *  "preOrderInfo": {
 *   "totalFee": 299,  // 总费用
 *   “itemFee” : 299,  // 商品费用
 *   "couponCnt": 2, // 可用优惠券个数
 *   "couponInfo":
 *     {
 *       "id": 986,
 *       "code": "QWERTPOIUYEV",
 *       "type_desc": "抵扣券",
 *       "discount_desc": "5.0元",
 *       "trade_type": 40,
 *       "expiry_time": "2017-03-05",
 *       "coupon_desc": "暂不抵扣运费",
 *       "reason": "",
 *       "limit_type": 9
 *     }
 *   }
 *  }
 * }
 * 测试地址: http://localhost:3000/v5/print/getPreVipOrderInfo_v6_0?device=1&userId=299188&itemId=1260
 */
function getPreVipOrderInfo_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var itemId = checkUtil.numberFromReq(req, 'itemId')||0;
    var couponId = checkUtil.numberFromReq(req, 'couponId')||0;
    couponId = couponId <= 0 ? 0 : couponId;

    if(userId <= 0 || device<0 || itemId<=0) {
        return usersUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getPreVipOrderInfo_v6_0(userId, itemId, couponId, function (error, retInfo) {
        if (error) {
            console.log('v5/print.js getPreVipOrderInfo_v6_0 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, {preOrderInfo:retInfo},res);
    });
}
router.get('/getPreVipOrderInfo_v6_0', getPreVipOrderInfo_v6_0);
router.post('/getPreVipOrderInfo_v6_0', getPreVipOrderInfo_v6_0);

//----------------------------------------------------------------------
/**
 * 3-33: 获取 vip 订单可用优惠券列表
 * 参数: device
 * 参数: userId
 * 参数: flg:  0 标示获取不可使用的优惠券, 1 标示获取可使用的优惠券
 * 参数: pageNum
 * 参数: pageSize
 * 参数[可选]: withTotalPage
 * 返回值:
 * {
 * "success": 1,
 * "msg": "成功",
 * "data": {
 *   "coupons": [
 *     {
 *       "id": 986,
 *       "code": "QWERTPOIUYEV",
 *       "type_desc": "抵扣券",
 *       "discount_desc": "5.0元",
 *       "trade_type": 20,
 *       "expiry_time": "2017-03-05",
 *       "coupon_desc": "暂不抵扣运费",
 *       "reason": "",
 *       "limit_type": 9
 *     }
 *   ],
 *   "totalPage": 1
 *  }
 * }
 * 测试地址: http://localhost:3000/v5/print/getVipOrderCoupons_v6_0?device=1&userId=299188&flg=0&pageNum=0&pageSize=100
 */
function getVipOrderCoupons_v6_0(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId')||0;
    var flg = checkUtil.numberFromReq(req, 'flg')||0;
    var itemId = checkUtil.numberFromReq(req, 'itemId')||0;
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    var withTotalPage = checkUtil.numberFromReq(req, 'withTotalPage')||0;
    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getVipOrderCoupons_v6_3(itemId, userId, flg, pageNum, pageSize, withTotalPage, function (error, retData) {
        if (error) {
            console.log('v5/print.js getVipOrderCoupons_v6_0 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getVipOrderCoupons_v6_0', getVipOrderCoupons_v6_0);
router.post('/getVipOrderCoupons_v6_0', getVipOrderCoupons_v6_0);

/**
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: pageNum	 请求页
 * 参数: pageSize	 请求页大小
 *
 * 测试地址: http://localhost:3000/v5/print/getShopCartGoodsListForWeb_v6_1?deive=1&userId=299174&pageNum=0&pageSize=100
 * */
function getShopCartGoodsListForWeb_v6_1(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var uuid = checkUtil.stringFromReq(req, 'uuid');

    var userId = checkUtil.numberFromReq(req, 'userId');
    var pageNum = checkUtil.numberFromReq(req, 'pageNum')||0;
    var pageSize = checkUtil.numberFromReq(req, 'pageSize')||12;
    if(pageSize <= 0) {
        pageSize = 12;// 默认值
    }
    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getShopCartGoodsListForWeb_v6_1(userId, pageNum, pageSize, function(err, retData){
        if(err) {
           console.log('v5/print.js getShopCartGoodsListForWeb_v6_1 Err: '+err);
           return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
    });
}
router.get('/getShopCartGoodsListForWeb_v6_1', getShopCartGoodsListForWeb_v6_1);
router.post('/getShopCartGoodsListForWeb_v6_1', getShopCartGoodsListForWeb_v6_1);



/**
 * 获取购物车商品信息
 *
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 *
 * 测试地址: http://localhost:3000/v5/print/getUserShopCartCnt_v6_2?device=1&userId=299174
 * */

function getUserShopCartCnt_v6_2(req, res, next) {
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    if(userId <= 0) {
        return printUtil.ret_func_json(0, '参数错误', {}, res);
    }

    printUtil.getUserShopCartCnt_v6_2(userId, null,function(error, cntInfo) {

        if(error) {
            console.log('v5/print.js getUserShopCartCnt_v6_2 Err: '+error);
            return printUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        return printUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,cntInfo,res);
    });
}
router.get('/getUserShopCartCnt_v6_2', getUserShopCartCnt_v6_2);
router.post('/getUserShopCartCnt_v6_2', getUserShopCartCnt_v6_2);


//--------------------------------------------------------------------------------
/**
 * 获取订单物流信息
 * 参数: device	"0表示从p0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	 用户唯一标识
 * 参数: orderId	 请求页
 "data": {
    "orderId": 986,
    "detailItems": [], // 订单子项目信息, 与详情一致, 此处忽略
    "addressInfo" : {}, // 地址信息, 与详情一致, 此处忽略
    "name": "中通快递",
    "no": "33982123",
    "state": 0, //'当前快递状态：0未知，1揽件中，2在途中，3派件中，4已签收，5派件失败/拒签，6疑难/问题件，7退回',
    "list": [
      {
        "time": "2017-09-29 09:27:03",
        "status": "[武汉市] 快件已到达武昌关南,业务员曙光星城周俊[15717167682]正在派件"
      }
    ]
  }
 }
 http://localhost:3000/v5/print/getOrderLogisticsInfo_v6_3?device=1&userId=299163&orderId=1706
 * */
// todo 新增接口, 待实现 begin
function getLogisticsInfo_v6_3(req, res, next) {
    //参数声明
    var device = checkUtil.numberFromReq(req, 'device');
    var userId = checkUtil.numberFromReq(req, 'userId');
    var orderId = checkUtil.numberFromReq(req, 'orderId');
    //参数判断
    if(userId == 0) {
        return usersUtil.ret_func_json(0, 'userId 为空', {}, res);
    }
    //参数判断
    if(orderId == 0) {
        return usersUtil.ret_func_json(0, 'orderId 为空', {}, res);
    }
    printUtil.getLogisticsInfo_v6_3(userId, orderId, function (getLogiErr, data) {
        if (getLogiErr) {
            console.log('/v5/print.js [getOrderLogisticsInfo_v6_3] err: ' + getLogiErr);
            var errMsg = typeof getLogiErr == 'string' ? getLogiErr : CODE.OPERATION_FAILED;
            return printUtil.ret_func_json(0, errMsg, {}, res);
        }

        return usersUtil.ret_func_json(1,CODE.OPERATION_SUCCESS, data,res);
    });
}
router.get('/getOrderLogisticsInfo_v6_3', getLogisticsInfo_v6_3);
router.post('/getOrderLogisticsInfo_v6_3', getLogisticsInfo_v6_3);



//==============================================================getUserOrderList_v5_5=================================
module.exports = router;
